/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.app.dto.MyOrderItemDto;
import com.yami.shop.bean.dto.StatisticsRefundDto;
import com.yami.shop.bean.enums.OrderType;
import com.yami.shop.bean.enums.RefundType;
import com.yami.shop.bean.enums.ReturnMoneyStsType;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.OrderRefund;
import com.yami.shop.bean.param.PayTopParam;
import com.yami.shop.bean.param.ProdAnalysisSurveyParam;
import com.yami.shop.bean.vo.OrderDetailVO;
import com.yami.shop.bean.vo.OrderItemDetailVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.OrderItemMapper;
import com.yami.shop.dao.OrderMapper;
import com.yami.shop.dao.OrderRefundMapper;
import com.yami.shop.service.OrderItemService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lgh on 2018/09/15.
 */
@Service
@AllArgsConstructor
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements OrderItemService {

    private final OrderItemMapper orderItemMapper;

    private final OrderMapper orderMapper;

    private final OrderRefundMapper orderRefundMapper;

    private final MapperFacade mapperFacade;

    @Override
    public List<OrderItem> getOrderItemsByOrderNumber(String orderNumber, Integer lang) {
        return orderItemMapper.listByOrderNumber(orderNumber, lang);
    }

    @Override
    public List<OrderItem> getUnGiveawayOrderItemsByOrderNumber(String orderNumber, Integer lang) {
        return orderItemMapper.getUnGiveawayOrderItemsByOrderNumber(orderNumber, lang);
    }

    @Override
    public IPage<PayTopParam> getPayAmounts(PageParam<OrderItem> page, ProdAnalysisSurveyParam param, Integer dbLang) {
        IPage<PayTopParam> resPage = orderItemMapper.getPayAmounts(page, param, dbLang);
        return resPage;
    }

    @Override
    public Integer getPayPersonNumByParam(Integer prodId, Long shopId, Date startTime, Date endTime) {
        return orderItemMapper.getPayPersonNumByParam(prodId, shopId, startTime, endTime);
    }

    @Override
    public void insertBatchOrderItem(List<OrderItem> orderItems) {
        saveBatch(orderItems);
        orderItemMapper.insertBatchOrderItemLang(orderItems);
    }

    @Override
    public OrderItem getByOrderItemId(Long orderItemId, Integer lang) {
        return orderItemMapper.getByOrderItemId(orderItemId, lang);
    }

    @Override
    public OrderItem getByOrderItemId(Long orderItemId) {
        return orderItemMapper.getInfoByOrderItemId(orderItemId);
    }

    @Override
    public OrderDetailVO listDetailByParam(String orderNumber, String refundSn) {
        Integer lang = I18nMessage.getLang();
        Order order = orderMapper.getOrderByOrderNumber(orderNumber);
        OrderDetailVO orderDetailVO = mapperFacade.map(order, OrderDetailVO.class);
        // 订单项信息
        List<OrderItemDetailVO> orderItems = orderItemMapper.listDetailByOrderNumber(orderNumber, order.getShopId(), lang);
        List<OrderItemDetailVO> orderItemDetailList = new ArrayList<>();
        OrderRefund orderRefundVO = null;
        if (StrUtil.isNotBlank(refundSn)) {
            orderRefundVO = orderRefundMapper.getOrderRefundByRefundSn(refundSn);
        }
        List<String> giveawayIds = new ArrayList<>();
        if (Objects.nonNull(orderRefundVO)) {
            String returnGiveawayIds = orderRefundVO.getReturnGiveawayIds();
            if (Objects.nonNull(returnGiveawayIds)) {
                giveawayIds = Arrays.asList(returnGiveawayIds.split(","));
            }
        }
        for (OrderItemDetailVO detailVO : orderItems) {
            if (Objects.equals(order.getOrderType(), OrderType.SECKILL.value())) {
                detailVO.setSeckillAmount(detailVO.getMultishopReduce());
            } else if (Objects.equals(order.getOrderType(), OrderType.GROUP.value())) {
                detailVO.setGroupAmount(detailVO.getMultishopReduce());
            }
            if (Objects.equals(order.getShopId(), Constant.PLATFORM_SHOP_ID)) {
                detailVO.setShopName(Constant.PLATFORM_SHOP_NAME);
            }
            OrderItemDetailVO orderItemDetailVO = mapperFacade.map(detailVO, OrderItemDetailVO.class);
            orderItemDetailVO.setRefundAmount(0.00);
            if (Objects.isNull(orderItemDetailVO.getPlatformShareReduce())) {
                orderItemDetailVO.setPlatformShareReduce(0.00);
            }
            orderItemDetailVO.setRefundCount(0);
            if (Objects.nonNull(orderRefundVO) && Objects.equals(orderRefundVO.getOrderItemId(), 0L)) {
                orderItemDetailVO.setRefundCount(detailVO.getProdCount());
                orderItemDetailVO.setRefundAmount(detailVO.getActualTotal());
            } else if (Objects.nonNull(orderRefundVO) && !Objects.equals(orderRefundVO.getOrderItemId(), 0L)) {
                if (Objects.equals(orderRefundVO.getOrderItemId(), detailVO.getOrderItemId())) {
                    orderItemDetailVO.setRefundCount(orderRefundVO.getGoodsNum());
                    orderItemDetailVO.setRefundAmount(orderRefundVO.getRefundAmount());
                }
                //赠品
                if (CollUtil.isNotEmpty(giveawayIds) && giveawayIds.contains(detailVO.getOrderItemId().toString())) {
                    orderItemDetailVO.setRefundCount(orderRefundVO.getGoodsNum());
                }
            }
            orderItemDetailList.add(orderItemDetailVO);
        }
        orderDetailVO.setOrderItemDetailList(orderItemDetailList);
        orderDetailVO.setFreeFreightAmount(order.getFreeTransfee());
        orderDetailVO.setPlatformFreeFreightAmount(order.getPlatformFreeFreightAmount());
        orderDetailVO.setFreightAmount(order.getFreightAmount());
        return orderDetailVO;
    }

    @Override
    public Integer getOrderItemProdNum(Long orderItemId) {
        return orderItemMapper.getOrderItemProdNum(orderItemId);
    }

    @Override
    public OrderItem getByIdI18n(Long orderItemId) {
        return orderItemMapper.getByOrderItemId(orderItemId, I18nMessage.getLang());
    }

    @Override
    public List<OrderItem> listAndPayTimeByOrderNumber(String orderNumber) {
        List<OrderItem> orderItems = orderItemMapper.listAndPayTimeByOrderNumber(orderNumber, I18nMessage.getDbLang());
        Set<Long> refundOrderItemIdSet = new HashSet<>();
        for (OrderItem orderItem : orderItems) {
            // 找出退款成功的订单项（退款成功的订单项无法评价）
            if (Objects.equals(orderItem.getRefundType(), RefundType.SINGLE.value()) && Objects.equals(orderItem.getReturnMoneySts(), ReturnMoneyStsType.SUCCESS.value())) {
                refundOrderItemIdSet.add(orderItem.getOrderItemId());
                if (StrUtil.isNotBlank(orderItem.getReturnGiveawayIds())) {
                    String returnGiveawayIds = orderItem.getReturnGiveawayIds();
                    String[] giveawayIds = returnGiveawayIds.split(StrUtil.COMMA);
                    for (String giveawayId : giveawayIds) {
                        refundOrderItemIdSet.add(Long.parseLong(giveawayId));
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(refundOrderItemIdSet)) {
            Iterator<OrderItem> iterator = orderItems.iterator();
            while (CollectionUtil.isNotEmpty(refundOrderItemIdSet)){
                OrderItem orderItem = iterator.next();
                if (refundOrderItemIdSet.contains(orderItem.getOrderItemId())){
                    iterator.remove();
                    refundOrderItemIdSet.remove(orderItem.getOrderItemId());
            }
        }
    }
        return orderItems;
}

    @Override
    public List<PayTopParam> getOrderProdPayCount(StatisticsRefundDto statisticsRefundDto, Integer dbLang) {
        if (Objects.isNull(statisticsRefundDto.getSize())) {
            statisticsRefundDto.setSize(10);
        }
        return orderItemMapper.getOrderProdPayCount(statisticsRefundDto, dbLang);
    }


//    @Override
//    public List<OrderItem> getUnCloseRefundOrderItemByOrderNumber(String orderNumber) {
//        return orderItemMapper.getUnCloseRefundOrderItemByOrderNumber(orderNumber);
//    }

}
